package com.csu.service.serviceImpl;

import com.csu.entity.Chat;
import com.csu.entity.ChatInfo;
import com.csu.entity.GroupChat;
import com.csu.mapper.*;
import com.csu.service.ChatService;
import com.csu.service.UserService;
import com.csu.util.MyWebSocket;
import com.csu.vo.ChatInfoVo;
import com.csu.vo.ChatVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * 对聊天功能提供业务逻辑
 */
@Service
public class ChatServiceImpl implements ChatService {
    @Autowired
    private GroupChatMapper groupChatMapper;
    @Autowired
    private ChatMapper chatMapper;
    @Autowired
    private ChatInfoMapper chatInfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserHeadPictureMapper userHeadPictureMapper;
    private static String imgUrl = "http://106.53.100.120:80/img/ql.jpg";
    /**
     *
     * @param chatId
     * @param chatTitle
     * @return boolean
     * 修改对话标题
     */
    @Override
    public String updateChatTitle(int chatId, String chatTitle) {
        //判断它是不是群聊
        if (groupChatMapper.getChatByChatId(chatId).getChatType() == 1){
            if (groupChatMapper.updateChatTitle(chatId, chatTitle) == 1)
                return "success";
            else
                return "对话标题修改失败！";
        }
        else
            return "私聊无法修改对话标题!";
    }

    /**
     * 判断是否是群主
     * @param chatId
     * @param userId
     * @return boolean
     */

    @Override
    public boolean isGroupOwner(int chatId, int userId) {
        GroupChat groupChat = groupChatMapper.getChatByChatId(chatId);
        if (groupChat.getUserId() == userId)
            return true;
        else
            return false;
    }

    /**
     * 通过userId获取聊天列表
     * @param userId
     * @return List<ChatVo>
     */

    @Override
    public List<ChatVo> getChatList(int userId) {
        //获取chatId列表
        List<Integer> chatIdList = chatMapper.getChatList(userId);
        System.out.println(chatIdList);
        List<ChatVo> chatVos = new ArrayList<>();
        for (int chatId : chatIdList){
            ChatVo chatVo = new ChatVo();
            chatVo.setChatId(chatId);

            //获取聊天名字，私聊是对方的名字
            GroupChat groupChat = groupChatMapper.getChatByChatId(chatId);
            //群聊
            if (groupChat.getChatType() == 1){
                chatVo.setGroupName(groupChat.getGroupName());
                chatVo.setImgurl(imgUrl);
            }
            else{
                //当群主是我的时候
                if(userId == groupChat.getUserId()){
                    chatVo.setGroupName(groupChat.getGroupName());
                    List<Integer> userList = chatMapper.getChatsOfUserId(groupChat.getChatId());
                    //获取对方的ID并查取头像
                    for (Integer userIdOfChat : userList){
                        if (userIdOfChat != userId)
                            chatVo.setImgurl(userHeadPictureMapper.getHeadPicture(userIdOfChat));
                    }
                }
                else {
                    chatVo.setGroupName(userMapper.getUsernameById(groupChat.getUserId()));
                    chatVo.setImgurl(userHeadPictureMapper.getHeadPicture(groupChat.getUserId()));
                }
            }

            //获取chatId对应的聊天未读的信息数量
            chatVo.setNewMsg(chatMapper.getUnreadCount(chatId,userId));
            ChatInfo chatInfo = chatInfoMapper.getLastChatInfo(chatId);
            if (chatInfo != null){
                //获取最新消息
                String newMessage =chatInfo.getInformation();
                String username = userMapper.getUsernameById(chatInfo.getUserId());
                chatVo.setMessage(username+":"+newMessage);
            }
            chatVos.add(chatVo);
        }
        return chatVos;
    }

    /**
     * 创建群聊（私聊or群聊）
     * @param userId
     * @param groupName
     * @param chatType
     * @return
     */
    @Override
    public int createChat(int userId, String groupName, int chatType) {
        GroupChat groupChat = new GroupChat();
        groupChat.setChatType(chatType);
        groupChat.setUserId(userId);
        groupChat.setGroupName(groupName);
        groupChatMapper.insertGroupChat(groupChat);
        //返回chatId
        return groupChat.getChatId();
    }

    /**
     * 添加用户和聊天的绑定关系
     * @param userId
     * @param chatId
     * @return int
     */
    @Override
    public int addBoundBetweenUserAndChat(int userId, int chatId) {
        Chat chat = new Chat();
        chat.setChatId(chatId);
        chat.setUserId(userId);
        chat.setUnreadCount(0);

        return chatMapper.insertChat(chat);
    }

    /**
     * 删除所有与此聊天有关的所有信息
     * @param chatId
     * @return int
     */

    @Override
    public int deleteChat(int chatId) {
        Integer msgCount = groupChatMapper.deleteGroupChat(chatId);
        chatMapper.deleteChat(chatId);
        chatInfoMapper.deleteChatInfo(chatId);
        return msgCount;
    }

    /**
     * 获取当前聊天中的用户列表
     * @param chatId
     * @return List<Integer>
     */

    @Override
    public List<Integer> getChats(int chatId) {
        return chatMapper.getChatsOfUserId(chatId);
    }

    /**
     * 插入聊天详情
     * @param chatInfo
     * @return int
     */
    @Override
    public int insertChatInfo(ChatInfo chatInfo) {
        return chatInfoMapper.insertChatInfo(chatInfo);
    }

    /**
     * 把未读信息加1
     * @param chatId
     * @param userId
     * @return int
     */
    @Override
    public int addUnreadCount(int chatId, int userId) {
        return chatMapper.addUnreadCount(chatId, userId);
    }

    /**
     * 获取聊天详情列表
     * @param chatId
     * @return List<ChatInfoVo>
     */
    @Override
    public List<ChatInfoVo> getChatInfoList(int chatId) {
        //获取一个聊天详情的列表
        List<ChatInfo> chatInfos = chatInfoMapper.getChatInfoListByChatId(chatId);
        System.out.println(chatInfos);
        return ChatInfoToCharInfoVo(chatInfos);
    }

    /**
     * 把未读信息设为1
     * @param userId
     * @param chatId
     * @return
     */
    @Override
    public Integer watchChat(int userId, int chatId) {
        return chatMapper.watchChat(userId, chatId);
    }

    /**
     * 查询是否两人已经存在私聊，如果存在则返回chatId,否则返回-1
     * @param senderId
     * @param recipientId
     * @return
     */
    @Override
    public ChatVo isExistPrivateChat(int senderId, int recipientId) {
        ChatVo chatVo = new ChatVo();
        List<GroupChat> groupChats = groupChatMapper.getChatListByUserId(senderId);
        List<GroupChat> groupChats1 = groupChatMapper.getChatListByUserId(recipientId);
        List<Integer> chaIds = new ArrayList<>();
        chaIds.addAll(getChatIdListByGroupChatList(groupChats));
        chaIds.addAll(getChatIdListByGroupChatList(groupChats1));
        for (Integer chatId : chaIds){
            List<Integer> userIds = chatMapper.getChatsOfUserId(chatId);
            //看能不能查到已经存在的私聊
            if (userIds.contains(senderId) && userIds.contains(recipientId)){
                GroupChat groupChatUser = groupChatMapper.getChatByChatId(chatId);
                chatVo.setGroupName(userMapper.getUsernameById(recipientId));
                chatVo.setChatId(chatId);
                chatVo.setImgurl(userHeadPictureMapper.getHeadPicture(recipientId));
                return chatVo;
            }
        }
        return null;
    }

    /**
     * 聊天详情转化为VO
     */
    public List<ChatInfoVo> ChatInfoToCharInfoVo(List<ChatInfo> chatInfos){
        List<ChatInfoVo> chatInfoVos = new ArrayList<>();
        for (ChatInfo chatInfo : chatInfos){
            ChatInfoVo chatInfoVo = new ChatInfoVo();
            String chatDate = chatInfo.getChatDate().toString();
            String result = chatDate.substring(0, chatDate.lastIndexOf(":"));
            chatInfoVo.setChatDate(result);
            chatInfoVo.setChatInfoId(chatInfo.getChatInfoId());
            chatInfoVo.setInformation(chatInfo.getInformation());
            chatInfoVo.setUserName(userMapper.getUsernameById(chatInfo.getUserId()));
            chatInfoVo.setUserId(chatInfo.getUserId());
            chatInfoVo.setChatId(chatInfo.getChatId());
            chatInfoVo.setType(chatInfo.getType());
            chatInfoVo.setVoiceurl(chatInfo.getVoiceurl());
            chatInfoVo.setImgurl(userHeadPictureMapper.getHeadPicture(chatInfo.getUserId()));

            chatInfoVos.add(chatInfoVo);
        }
        return chatInfoVos;
    }
    public List<Integer> getChatIdListByGroupChatList(List<GroupChat> groupChats){
        List<Integer> chatIds = new ArrayList<>();
        for (GroupChat groupChat : groupChats){
            if (groupChat.getChatType() == 0)
            chatIds.add(groupChat.getChatId());
        }
        return chatIds;
    }
}
